/*
   @Copyright:LintCode
   @Author:   tjyemail
   @Problem:  http://www.lintcode.com/problem/best-time-to-buy-and-sell-stock-iii
   @Language: C++
   @Datetime: 16-02-09 05:43
   */

class Solution {
public:
	/**
	 * @param prices: Given an integer array
	 * @return: Maximum profit
	 */
	int maxProfit(vector<int> &prices) {
		// write your code here
		if(prices.size()<2) return 0;
		int n=prices.size();
		vector<int> left(n,0), right(n,0);
		for(int i=1, mx=prices[0]; i<n; ++i){
			mx=min(mx,prices[i]);
			left[i]=max(left[i-1],prices[i]-mx);
		}
		for(int i=n-1, mx=prices[n-1]; i--;){
			mx=max(mx,prices[i]);
			right[i]=max(right[i+1],mx-prices[i]);
		}
		int profit=0;
		for(int i=0; i<n; ++i)
			profit=max(profit,left[i]+right[i]);
		return profit;
	}
};
